package stateapi

import (
	"iot-base/common/dbconn"
	"iot-base/common/dbobj"
	"iot-base/common/webapi"
	"time"

	"github.com/gin-gonic/gin"
)

type TimePriod struct {
	Begin          time.Time `json:"begin"`
	End            time.Time `json:"end"`
	PeriodAsMinute int64     `json:"period_as_minute"`
}

type StateInfo struct {
	StateNow        int         `json:"state_now"`
	OnlineTimeTotal float64     `json:"online_time_total"`
	Histroy         []TimePriod `json:"history"`
}

func GetStateHistroy(tid string) (StateInfo, error) {
	var alines []TimePriod
	var firstOffline TimePriod
	var info StateInfo
	err := dbconn.DBConnection.Raw("select create_time as begin,first_online_time as end  from thing_maintain_infos tmi where tmi.thing_id = ?", tid).First(&firstOffline).Error

	if err != nil {
		return info, err
	}
	if firstOffline.End.Unix() > firstOffline.Begin.Unix() {
		alines = append(alines, firstOffline)
	}

	var alarmPriods []TimePriod
	err = dbconn.DBConnection.Raw(`select alarm_time as begin,clear_time as end from 
		alarm_histroys ah where ah.t_id = ? and ah.alarm_id = 'offline' 
		and date(alarm_time) > (now() - interval '1 month') order by alarm_time`, tid).Find(&alarmPriods).Error
	if err == nil {
		if len(alarmPriods) > 0 && len(alines) > 0 {
			if alines[0].End.Unix() > alarmPriods[0].Begin.Unix() {
				alines[0].End = firstOffline.Begin
			}
		}
		alines = append(alines, alarmPriods...)

	}
	var state dbobj.ThingState
	err = dbconn.DBConnection.Where("thing_id=?", tid).First(&state).Error
	if err == nil {
		if state.State == 0 { //最后状态为不在线
			alines = append(alines, TimePriod{
				Begin: state.ChangedTime,
				End:   time.Now(),
			})

		} else {
			alines = append(alines, TimePriod{
				Begin: time.Now(),
			})
		}
		info.StateNow = state.State
		//nlen := len(alines)
		var total float64
		for i := 0; i < len(alines)-1; i++ {
			alines[i].Begin = alines[i].End
			alines[i].End = alines[i+1].Begin
			diff := alines[i].End.Unix() - alines[i].Begin.Unix()
			if diff <= 5*60 {
				alines = append(alines[:i], alines[i+1:]...)
				i--
				continue
			}
			alines[i].PeriodAsMinute = diff / 60
			total += float64(diff)
		}
		info.OnlineTimeTotal = total / float64(60)
		alines = alines[:len(alines)-1]
	}
	info.Histroy = alines
	return info, nil

}

func InitOnlineAPI(r *gin.RouterGroup) {
	s := r.Group("/state")
	{
		s.GET("/online/:tid", func(c *gin.Context) {
			tid := c.Param("tid")
			if tid == "" {
				webapi.SendError("tid 为空，请填写", webapi.ParamsError, c)
			}
			res, err := GetStateHistroy(tid)
			webapi.SendResult(res, err, c)
		})
	}

}
